package com.isoft.service.impl;

import com.isoft.entity.BaseCfieEntity;
import com.isoft.mapper.BaseCfieMapper;
import com.isoft.service.BaseCfieService;
import com.isoft.util.XmlParserUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class BaseCfieServiceImpl implements BaseCfieService {
    private static final Logger logger = LoggerFactory.getLogger(BaseCfieServiceImpl.class);

    @Autowired
    private BaseCfieMapper baseCfieMapper;

    @Autowired
    private XmlParserUtil xmlParserUtil;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String parseAndSave(String xmlContent) {
        try {
            if (xmlContent == null || xmlContent.trim().isEmpty()) {
                throw new IllegalArgumentException("XML content is empty");
            }

            BaseCfieEntity entity = xmlParserUtil.parseXml(xmlContent, BaseCfieEntity.class);

            if (entity == null || entity.getCrft() == null) {
                throw new IllegalArgumentException("Invalid BASE-CFIE XML structure");
            }

            processAircraftData(entity);

            return "Aircraft data processed successfully. Aircraft code: " + entity.getCrft().getCode();
        } catch (Exception e) {
            logger.error("BASE-CFIE XML processing failed", e);
            throw new RuntimeException("Failed to process BASE-CFIE XML: " + e.getMessage());
        }
    }

    private void processAircraftData(BaseCfieEntity entity) {
        try {
            // 1. 验证飞机数据
            if (entity.getCrft() == null) {
                throw new IllegalArgumentException("Aircraft data is null");
            }

            String aircraftType = entity.getCrft().getAircraftType();
            String aircraftNumber = entity.getCrft().getCode();

            if (aircraftType == null || aircraftType.trim().isEmpty()) {
                throw new IllegalArgumentException("Aircraft type is required");
            }

            if (aircraftNumber == null || aircraftNumber.trim().isEmpty()) {
                throw new IllegalArgumentException("Aircraft number is required");
            }

            // 2. 插入元数据前，强制dateTime为String，并打印类型和值
            if (entity.getMeta() != null && entity.getMeta().getDateTime() != null) {
                logger.debug("dateTime类型:{}，值:{}", entity.getMeta().getDateTime().getClass().getName(), entity.getMeta().getDateTime());
                entity.getMeta().setDateTime(entity.getMeta().getDateTime().replaceAll("[^0-9]", ""));
                logger.debug("dateTime清洗后类型:{}，值:{}", entity.getMeta().getDateTime().getClass().getName(), entity.getMeta().getDateTime());
            }
            baseCfieMapper.insertMeta(entity);
            logger.debug("Inserted meta data for aircraft: {}", aircraftNumber);

            // 3. 获取下一个可用的航班ID
            Long nextFlightId = baseCfieMapper.getNextFlightId();
            logger.debug("Next available flight ID: {}", nextFlightId);

            // 4. 插入虚拟航班记录
            baseCfieMapper.insertDummyFlight(nextFlightId);
            logger.debug("Inserted dummy flight with ID: {}", nextFlightId);

            // 5. 插入飞机记录并关联虚拟航班
            baseCfieMapper.insertAircraftWithFlight(
                    nextFlightId,
                    aircraftType,
                    aircraftNumber
            );
            logger.info("Successfully inserted aircraft record. Type: {}, Number: {}, Flight ID: {}",
                    aircraftType, aircraftNumber, nextFlightId);

            // 6. 新增：插入航班异常信息到FLIGHT_IRREGULARITY表
            try {
                baseCfieMapper.insertIrregularity(nextFlightId);
                logger.debug("插入航班异常信息成功，航班ID: {}", nextFlightId);
            } catch (Exception e) {
                logger.warn("插入航班异常信息失败，航班ID: {}", nextFlightId, e);
            }

        } catch (Exception e) {
            logger.error("Failed to process aircraft data. Aircraft: {}",
                    entity.getCrft() != null ? entity.getCrft().getCode() : "null", e);
            throw new RuntimeException("Aircraft data processing failed: " + e.getMessage(), e);
        }
    }
} 